﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using DocumentManagement.Models;
using System.Windows.Data;
using Microsoft.Win32;
using System.Windows;
using System.Data;
using System.IO;

namespace DocumentManagement.ViewsModels
{
   public class AddDocumentOutViewsModel : ViewsModelBase
    {
       string code;
        private QSHCEntities1 _entityModels;
        public QSHCEntities1 EntityModels
        {
            get { return _entityModels; }
            set
            {
                if (_entityModels != value)
                {
                    _entityModels = value;
                    OnPropertyChanged("EntityModels");
                }
            }
        }

        private CreateSend _mySend;
        public CreateSend MySend
        {
            get { return _mySend; }
            set
            {
                if (_mySend != value)
                {
                    _mySend = value;
                    OnPropertyChanged("MySend");

                    if (MySend != null)
                        AttachICV = CollectionViewSource.GetDefaultView(MySend.ScanSendAttacheds.Where(p => p.Active == true));
                }
            }
        }



        private ScanSendAttached _selectedAttachFile;
        public ScanSendAttached SelectedAttachFile
        {
            get { return _selectedAttachFile; }
            set
            {
                if (_selectedAttachFile != value)
                {
                    _selectedAttachFile = value;
                    OnPropertyChanged("SelectedAttachFile");
                }
            }
        }

        private bool _myAction1;
        public bool MyAction1
        {
            get { return _myAction1; }
            set
            {
                if (_myAction1 != value)
                {
                    _myAction1 = value;
                    OnPropertyChanged("MyAction1");
                }
            }
        }
        private bool _myAction2;
        public bool MyAction2
        {
            get { return _myAction2; }
            set
            {
                if (_myAction2 != value)
                {
                    _myAction2 = value;
                    OnPropertyChanged("MyAction2");
                }
            }
        }

        private bool _myspeed1;
        public bool MySpeed1
        {
            get { return _myspeed1; }
            set
            {
                if (_myspeed1 != value)
                {
                    _myspeed1 = value;
                    OnPropertyChanged("MySpeed1");
                }
            }
        }
        private bool _myspeed2;
        public bool MySpeed2
        {
            get { return _myspeed2; }
            set
            {
                if (_myspeed2 != value)
                {
                    _myspeed2 = value;
                    OnPropertyChanged("MySpeed2");
                }
            }
        }
        private bool _myspeed3;
        public bool MySpeed3
        {
            get { return _myspeed3; }
            set
            {
                if (_myspeed3 != value)
                {
                    _myspeed3 = value;
                    OnPropertyChanged("MySpeed3");
                }
            }
        }
        private bool _myspeed4;
        public bool MySpeed4
        {
            get { return _myspeed4; }
            set
            {
                if (_myspeed4 != value)
                {
                    _myspeed4 = value;
                    OnPropertyChanged("MySpeed4");
                }
            }
        }

        private bool _myTypeDoc1;
        public bool MyTypeDoc1
        {
            get { return _myTypeDoc1; }
            set
            {
                if (_myTypeDoc1 != value)
                {
                    _myTypeDoc1 = value;
                    OnPropertyChanged("MyTypeDoc1");
                }
            }
        }
        private bool _myTypeDoc2;
        public bool MyTypeDoc2
        {
            get { return _myTypeDoc2; }
            set
            {
                if (_myTypeDoc2 != value)
                {
                    _myTypeDoc2 = value;
                    OnPropertyChanged("MyTypeDoc2");
                }
            }
        }

        private ICollectionView _attachICV;
        public ICollectionView AttachICV
        {
            get { return _attachICV; }
            set
            {
                if (_attachICV != value)
                {
                    _attachICV = value;
                    OnPropertyChanged("AttachICV");
                }
            }
        }
        //private ICollectionView _sendICV;
        //public ICollectionView SendICV
        //{
        //    get { return _sendICV; }
        //    set
        //    {
        //        if (_sendICV != value)
        //        {
        //            _sendICV = value;
        //            OnPropertyChanged("SendICV");
        //        }
        //    }
        //}

        public AddDocumentOutViewsModel()
        {
            //if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            //{
            //    //EntityModels = new QSHCEntities1();

            //}
        }

        public void GetBrowse()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.DefaultExt = ".txt";
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                // Open document
                var filename = (MySend.CreateSendDate.Year + 543).ToString("D4") + MySend.CreateSendDate.Month.ToString("D2") + MySend.CreateSendDate.Day.ToString("D2") + "_" + dlg.SafeFileName;

                //TxtPath = dlg.FileName;

                var AddToDataGrid = new ScanSendAttached { FileName = filename, FilePathSend = dlg.FileName, Active = true };
                MySend.ScanSendAttacheds.Add(AddToDataGrid);

                AttachICV.Refresh();

            }
        }

        public void SaveToDatabase()
        {
          
          
      
            ////ชั้นความเร็ว
            if (MySpeed1 == true) MySend.Speed = 1;
            else if (MySpeed2 == true) MySend.Speed = 2;
            else if (MySpeed3 == true) MySend.Speed = 3;
            else if (MySpeed4 == true) MySend.Speed = 4;

            //การปฏิบัติ
            if (MyAction1 == true) MySend.Action = 1;
            else MySend.Action = 2;

            if (MyTypeDoc1 == true) MySend.Type = 1;
            else MySend.Type = 2;
            // Check MyReceive EntityState
            if (MySend.EntityState == EntityState.Added || MySend.EntityState == EntityState.Detached) //detached ดึงข้อมูลมาจากดาต้าเบสแล้วมีการแก้ไข
            {
                MySend.LogData = CreateLogData(LogAction.Create, MySend.CreateSendID);
                MySend.Active = true;
                EntityModels.CreateSends.AddObject(MySend);
            }
            else if (MySend.EntityState == EntityState.Detached)// มีการแก้ไขข้อมูล
            {

                MySend.LogData = CreateLogData(LogAction.Edit, MySend.CreateSendID);
            }

            // Check ReceiveAttachedFiles EntityState
            foreach (var item in MySend.ScanSendAttacheds)
            {
                if (item.EntityState == EntityState.Added || item.EntityState == EntityState.Detached)
                {
                    File.Copy(item.FilePathSend, "D:\\uploadSend\\" + item.FileName, true);
                }
                else if (item.EntityState == EntityState.Modified)
                {
                    if (File.Exists("D:\\uploadSend\\" + item.FileName))
                    {
                        File.Delete("D:\\uploadSend\\" + item.FileName);
                    }
                }
            }

            EntityModels.SaveChanges();

            //Clear Data And Autonumber
            MySend = new CreateSend { CreateSendDate = DateTime.Now };
            //GetAutoNumber();
        }


        public void DeleteFile()
        {
            SelectedAttachFile.Active = false;

            if (SelectedAttachFile.EntityState == EntityState.Added || SelectedAttachFile.EntityState == EntityState.Detached)
            {
                MySend.ScanSendAttacheds.Remove(SelectedAttachFile);
                AttachICV.Refresh();
            }
            else if (SelectedAttachFile.EntityState == EntityState.Modified)
            {
                AttachICV.Refresh();
            }

        }

        public void GetAutoNumber()
        {
            string year = Convert.ToString(DateTime.Today.Year + 543);

            try
            {

                //foreach (var item in EntityModels.Sends.Where(p => p.Status == 2))
                //{
                //    code = item.SendCode.ToString();

                //    MessageBox.Show(code);
                  
                //}

                string AutoNum = EntityModels.CreateSends.OrderByDescending(p => p.CreateSendCode).Where(p => p.Type == 2).First().CreateSendCode;
                var firstcode = AutoNum.Substring(17, 4);
                var lastcode = Convert.ToInt32(AutoNum.Substring(22, 4));

                if (firstcode != year)
                {
                    MySend.CreateSendCode = string.Format("{0}/{1}.{2}", "ศธ 0514.7.5.1.10", year, "0001");
                }
                else
                {
                    MySend.CreateSendCode = string.Format("{0}/{1}.{2}", "ศธ 0514.7.5.1.10", year, (lastcode + 1).ToString("D4"));//digital string 4 ตัว เช่น 0003
                }
               
                
                   
              
              
               
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                MySend.CreateSendCode = string.Format("{0}/{1}.{2}", "ศธ 0514.7.5.1.10", year, "0001");
            }


        }
       



        public LogData CreateLogData(LogAction logAction, int primaryKeyID)
        {
            LogData logData = new LogData
            {
                Employee = EntityModels.Employees.Where(p => p.EmployeeCode == "IT007").SingleOrDefault(),
                Action = (byte)logAction,
                LogDateTime = DateTime.Now,
                SchemaName = "BackOffice",
                TableName = "Sends",
                PrimaryKeyID = primaryKeyID,
            };
            return logData;
        }

        public enum LogAction
        {
            Login = 1,
            Logout,
            OpenPage,
            Create,
            Edit,
            Delete,
        }





      
    }
}
